package master;

import java.util.ArrayList;
import java.util.List;

/**
 * 全排列
 *
 * @author chenyw
 * @date 2022/7/25 15:34
 */
public class M46permute {
    public static void main(String[] args) {
        new M46permute().permute(new int[] {1,2,3});
    }
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> permute(int[] nums) {
        int n = nums.length;
        int[] visited = new int[n];
        List<Integer> list = new ArrayList<>();
        dfs(nums, list, visited);
        return res;
    }

    private void dfs(int[] nums, List<Integer> list, int[] visited) {
        if (list.size() == nums.length) {
            res.add(new ArrayList<>(list));
            return;
        }
        //进入for循环有两种情况，
        //1. 从dfs语句进入，i从零开始
        //2. 回溯之后，for循环一次结束，从i+ 1开始
        for (int i = 0; i < nums.length; i++) {
            if (visited[i] == 1) {
                continue;
            }
            visited[i] = 1;
            list.add(nums[i]);
//            System.out.println(list.toString());
//            StringBuilder sb = new StringBuilder();
//            for (int i1 : visited) {
//                sb.append(i1);
//            }
//            System.out.println(sb.toString());
            dfs(nums, list, visited);
            //递归回到i的位置，下面的语句执行完继续从i开始进入循环！！！！！！
            visited[i] = 0;
            list.remove(list.size() - 1);


//            System.out.println(list.toString());
//            StringBuilder sb2 = new StringBuilder();
//            for (int i1 : visited) {
//                sb2.append(i1);
//            }
//            System.out.println(sb2.toString());
        }
    }

}
